package com.afs.electronicforensics.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afs.electronicforensics.fragment.SignInFragment;
import com.afs.electronicforensics.utils.CheckPhone;
import com.afs.electronicforensics.utils.Constants;
import com.afs.electronicforensics.utils.SendCode;
import com.afs.electronicforensics.monitor.LoginMonitorEditText;
import com.afs.electronicforensics.utils.TimeCount;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ResetPasswordActivity extends AppCompatActivity {
    ImageView back;
    EditText phone,password,code;
    ConstraintLayout code_linearLayout;
    TextView sendCode,username,title,nextReset,submit;
    String userid;
    //验证码倒计时
    private TimeCount time;
    //手机号设置
    String tel = "";
    //验证码设置
    String word = "";
    //验证码设置
    char[] checkCode ={'0','1','2','3','4','5','6','7','8','9'};



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_password);

        back = findViewById(R.id.img_back);

        phone = findViewById(R.id.phone);
        username = findViewById(R.id.username);
        title = findViewById(R.id.title);

        code_linearLayout = findViewById(R.id.code_linearLayout);
        code = findViewById(R.id.code);
        sendCode = findViewById(R.id.send_code);
        time = new TimeCount(60000, 1000,sendCode);

        nextReset = findViewById(R.id.next_reset);

        password = findViewById(R.id.password);
        submit = findViewById(R.id.submit);




        new LoginMonitorEditText().SetMonitorEditText(nextReset,phone,code);
        new LoginMonitorEditText().SetMonitorEditText(submit,password);
        new LoginMonitorEditText().SetMonitorEditText(sendCode,phone);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


        sendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String pNo = phone.getText().toString().trim();
                if(pNo.length()==0||pNo.equals("")){
                    Toast.makeText(ResetPasswordActivity.this,"手机号码输入为空！",Toast.LENGTH_SHORT).show();
                }else if(!CheckPhone.isMobileNO(pNo)){
                    Toast.makeText(ResetPasswordActivity.this,"手机号码格式有误！",Toast.LENGTH_SHORT).show();
                    phone.setText(null);
                }else{
                    String path = Constants.URL_ROOT+"user/findByPhone?phone="+pNo;//判断手机号码是否存在
                    new Verification().execute(path);
                }
            }
        });

        nextReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getCode = code.getText().toString().trim();
                if(getCode.equals(word)&&!word.equals("")){
                    Toast.makeText(ResetPasswordActivity.this, "验证成功！", Toast.LENGTH_SHORT).show();
                    //跳转页面
                    String path = Constants.URL_ROOT+"user/findByPhone?phone="+phone.getText().toString().trim();//判断手机号码是否存在
                    new getUserName().execute(path);
                }else if(word.equals("")){
                    Toast.makeText(ResetPasswordActivity.this, "未获取验证码！", Toast.LENGTH_SHORT).show();
                    code.setText(null);
                } else{
                    Toast.makeText(ResetPasswordActivity.this, "验证码输入有误!", Toast.LENGTH_SHORT).show();
                    code.setText(null);
                }


            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String pwd = password.getText().toString().trim();
                String path1 = Constants.URL_ROOT + "user/updatePassword?password="+pwd+"&userId="+userid;
                new doResetPassword().execute(path1);
            }
        });


    }



    //发送验证码
    private class Verification extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//这个应该都知道是干嘛的，默认是GET
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String info = o.toString().trim();
            try {
                JSONObject js = new JSONObject(info);
                String result = js.getString("code").trim();
                if("0".equals(result)){
                    Toast.makeText(ResetPasswordActivity.this, "该手机号码未绑定用户！", Toast.LENGTH_SHORT).show();
                    phone.setText(null);
                }else if("1".equals(result)){
                    time.start();
                    tel = phone.getText().toString().trim();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for(int i=0;i<4;i++){
                                word+=checkCode[(int)(checkCode.length*Math.random())];
                            }
                            SendCode sc = new SendCode();
                            String json = sc.bowlingJson(word,tel);
                            try{
                                sc.post("https://open.ucpaas.com/ol/sms/sendsms",json);
                                Looper.prepare();
                                Toast.makeText(ResetPasswordActivity.this, "验证码已发送", Toast.LENGTH_SHORT).show();
                                Looper.loop();

                            }catch(IOException e) {
                                Looper.prepare();
                                Toast.makeText(ResetPasswordActivity.this, "验证码发送失败", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    //获取用户名
    private class getUserName extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//这个应该都知道是干嘛的，默认是GET  
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String info = o.toString().trim();
            try {
                JSONObject js = new JSONObject(info);
                String data = js.getString("data");
                JSONObject jo = new JSONObject(data);
                String userId = jo.getString("id").trim();
                String userName = jo.getString("name").trim();
                System.out.println(userName);
                if(o==null){
                    Toast.makeText(ResetPasswordActivity.this, "未知错误！返回登录页面！", Toast.LENGTH_SHORT).show();
                    onBackPressed();
                }else{
                    if("1".equals(js.getString("code"))) {
                        userid = userId;
                        phone.setVisibility(View.GONE);
                        nextReset.setVisibility(View.GONE);
                        code_linearLayout.setVisibility(View.GONE);
                        title.setText("重置密码");
                        username.setVisibility(View.VISIBLE);
                        username.setText("用户名：" + userName);//这里填入用户名
                        password.setVisibility(View.VISIBLE);
                        submit.setVisibility(View.VISIBLE);
                    }
                    else{
                        Toast.makeText(ResetPasswordActivity.this, "未知错误！返回登录页面！", Toast.LENGTH_SHORT).show();
                        onBackPressed();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //重置密码
    private class doResetPassword extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");//这个应该都知道是干嘛的，默认是GET
                conn.setConnectTimeout(5000);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
                conn.connect();

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String info = o.toString().trim();
            try {
                JSONObject jo = new JSONObject(info);
                String code = jo.getString("code").trim();
            if(code.equals("1")){
                Toast.makeText(ResetPasswordActivity.this, "重置密码成功！", Toast.LENGTH_SHORT).show();
                onBackPressed();
            }else{
                Toast.makeText(ResetPasswordActivity.this, "未知错误！返回登录页面！", Toast.LENGTH_SHORT).show();
                onBackPressed();
            }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}